define(['moment', 'module/moduleB/program/B0301/abnormal_detail'], function (moment) {
    return ['$scope', '$rootScope', '$filter', '$stateParams', '$mdDialog', 'config', 'MMWService', '$calculater', 'AbnormalService',
        function ($scope, $rootScope, $filter, $stateParams, $mdDialog, config, $MMWService, $calculater, $AbnormalService) {

            $scope.init = function () {
                $scope.adjustInfo = {
                    plot_no:'',
                    adjustment_detail: [],
                    adjustment_currently_detail:[]
                };

                $scope.adjustInfo_ori = {
                    plot_no: '',
                    adjustment_detail: [],
                    adjustment_currently_detail: []
                };

                $scope.total_ori_qty = 0;
                // 20220613 modify by Alan for#95492 : 宣告多於短少原始值及修改值
                $scope.ori_surplus_qty_total = [];
                $scope.ori_lack_qty_total = [];
                $scope.change_surplus_qty_total = [];
                $scope.change_lack_qty_total = [];
            };

            $scope.back = function () {
                $scope.$root.hideMenu();
                $scope.$root.changeProgram('home', true);
            };

            $scope.barcodeScan = function(event){
                if(event.keyCode == 13){
                    $scope.search();
                }
            };

            $scope.search = function () {
                if($scope.adjustInfo.plot_no && $scope.adjustInfo.plot_no!=''){
                    //MO7030101-005
                    var content = {plot_no: $scope.adjustInfo.plot_no};
                    adjustmentPlotInfoGet(content, function (response) {
                        if((response.adjustment_plot_info_get && response.adjustment_plot_info_get.length > 0)
                            || (response.adjustment_currently_detail && response.adjustment_currently_detail.length > 0)){

                            $scope.total_ori_qty=0;
                            if(response.adjustment_plot_info_get){
                                $scope.adjustInfo.adjustment_detail=response.adjustment_plot_info_get;
                            }
                            $scope.adjustInfo.adjustment_detail_hide = $scope.adjustInfo.adjustment_detail.length == 0;
                            // 20220613 modify by Alan for#95492 : 紀錄多於短少初始值及原始值
                            resetAbnormalQtyTotal();
                            for(var i=0;i<$scope.adjustInfo.adjustment_detail.length;i++){
                              $scope.total_ori_qty =$scope.total_ori_qty
                                  +parseInt($scope.adjustInfo.adjustment_detail[i].ori_quality)
                                  +parseInt($scope.adjustInfo.adjustment_detail[i].ori_defect);

                                $scope.adjustInfo.adjustment_detail[i].change_quality=$scope.adjustInfo.adjustment_detail[i].ori_quality;
                                $scope.adjustInfo.adjustment_detail[i].change_defect=$scope.adjustInfo.adjustment_detail[i].ori_defect;
                                $scope.adjustInfo.adjustment_detail[i].change_labor_hours=$scope.adjustInfo.adjustment_detail[i].labor_hours;
                                $scope.adjustInfo.adjustment_detail[i].change_machine_hours=$scope.adjustInfo.adjustment_detail[i].machine_hours;

                                var abnormal_detail = $scope.adjustInfo.adjustment_detail[i].abnormal_detail;
                                var ori_surplus_qty_total = getAbnormalQtyTotalBy(abnormal_detail, 11);
                                var ori_lack_qty_total = getAbnormalQtyTotalBy(abnormal_detail, 12);
                                $scope.ori_surplus_qty_total.push(ori_surplus_qty_total);
                                $scope.ori_lack_qty_total.push(ori_lack_qty_total);
                            }
                            $scope.change_surplus_qty_total = angular.copy($scope.ori_surplus_qty_total);
                            $scope.change_lack_qty_total = angular.copy($scope.ori_lack_qty_total);
                            $scope.total_change_qty = $scope.total_ori_qty;

                            if(response.adjustment_currently_detail){
                                $scope.adjustInfo.adjustment_currently_detail=response.adjustment_currently_detail;
                            }

                            if($scope.adjustInfo.adjustment_currently_detail && $scope.adjustInfo.adjustment_currently_detail.length>0){
                                $scope.adjustInfo.adjustment_currently_detail.forEach(function(temp){
                                    temp.change_qty = temp.qty;
                                });
                            }
                            $scope.adjustInfo.adjustment_currently_detail_hide = $scope.adjustInfo.adjustment_currently_detail.length == 0;

                            //為了防止兩個列表都關起來
                            if($scope.adjustInfo.adjustment_detail_hide && $scope.adjustInfo.adjustment_currently_detail_hide){
                                $scope.adjustInfo.adjustment_detail_hide = false;
                                $scope.adjustInfo.adjustment_currently_detail_hide = false;
                            }

                            //原始值
                            angular.copy($scope.adjustInfo, $scope.adjustInfo_ori);

                        } else {
                            $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                            $scope.adjustInfo.adjustment_detail = [];
                            $scope.adjustInfo.adjustment_currently_detail = [];
                        }
                    });
                } else {
                    $scope.$root.showAlert($filter('translate')('B0301.msg.plot_no_empty'));
                }
            };

            $scope.confirm = function () {
                var isWarnning = false,
                    content = {
                    plot_no : $scope.adjustInfo.plot_no,
                    adjustment_state_detail:[],
                    adjustment_detail: [],
                };

                for (var i = 0; i <  $scope.adjustInfo.adjustment_currently_detail.length; i++) {
                    var detail = $scope.adjustInfo.adjustment_currently_detail[i];
                    if(detail.qty != detail.change_qty){
                        content.adjustment_state_detail.push(detail);
                        //hasModified = true;
                        //break;
                    }
                }
                // 20220124 modify by Alan for#95492 : 增加新增使用者功能
                //新增參數，ori_qty，change_qty 
                for (var i = 0; i < $scope.adjustInfo.adjustment_detail.length; i++) {
                    for (var j = 0; j < $scope.adjustInfo.adjustment_detail[i].employees_detail.length; j++) {
                        if ($scope.adjustInfo_ori.adjustment_detail[i].employees_detail[j] === undefined) {
                            $scope.adjustInfo_ori.adjustment_detail[i].employees_detail[j] = {
                                USERNO: $scope.adjustInfo.adjustment_detail[i].employees_detail[j].USERNO,
                                USERNAME: $scope.adjustInfo.adjustment_detail[i].employees_detail[j].USERNAME,
                                RESVALUE: $scope.adjustInfo.adjustment_detail[i].employees_detail[j].USERNAME.RESVALUE,
                                inputqty: 0
                            };
                        }
                         //20220816 modify by wangzy for 0117202: 生产批一共有八件，显示完工，生产批历程表只有五件
                        //去除四舍五入按原值赋值
                        $scope.adjustInfo.adjustment_detail[i].employees_detail[j].ori_qty = $scope.adjustInfo_ori.adjustment_detail[i].employees_detail[j].inputqty;
                        $scope.adjustInfo.adjustment_detail[i].employees_detail[j].change_qty = $scope.adjustInfo.adjustment_detail[i].employees_detail[j].inputqty;
                    }
                }

                //歷程
                // 20210423 modify by 14581 for M#86547 : 資料重複寫入
                // 20220922 modify by Alan for M#119121 : 修正同類別不同原因數量相同但無法送出的問題
                for (var i = 0; i < $scope.adjustInfo.adjustment_detail.length; i++) {
                    var item = $scope.adjustInfo.adjustment_detail[i];
                    var oriItem = $scope.adjustInfo_ori.adjustment_detail[i];
                    var escape = false;
                    for (var j = 0; j < $scope.adjustInfo.adjustment_detail[i].employees_detail.length; j++) {
                        if ($scope.adjustInfo.adjustment_detail[i].employees_detail[j].inputqty != $scope.adjustInfo_ori.adjustment_detail[i].employees_detail[j].inputqty && !escape) {
                            content.adjustment_detail.push(item);
                            escape = true
                        }
                    }
                    if(!escape){
                        if((item.is_defect_change == 'Y')
                        || (item.ori_quality != item.change_quality)
                        || (item.labor_hours != item.change_labor_hours)
                        || (item.machine_hours != item.change_machine_hours)
                        || (JSON.stringify(item.abnormal_detail) != JSON.stringify(oriItem.abnormal_detail))){
                            content.adjustment_detail.push(item);
                        }
                    }
                    if (item.erp_no && item.erp_no != '') {
                        isWarnning = true;
                    }
                }

                if (content.adjustment_state_detail.length !=0 || content.adjustment_detail.length !=0) {
                    if(isWarnning){
                        $scope.$root.showConfirm($filter('translate')('B0301.msg.erp_rework'), function(dialog){
                            dialog.hide();
                            adjustmentPlotInfoProcess(content, function (response) {
                                $scope.$root.showToast($filter('translate')('B0301.msg.process_success'));
                                $scope.search();
                            });
                        });
                    } else {
                        adjustmentPlotInfoProcess(content, function (response) {
                            $scope.$root.showToast($filter('translate')('B0301.msg.process_success'));
                            $scope.search();
                        });
                    }
                }
                else {
                    $rootScope.showAlert($filter('translate')('B0301.showAlert'));
                }
            };

            $scope.input_plot_qty = function (event, item, column) {
                var target = event.currentTarget;
                angular.element(target).addClass('is-focus');
                var defaultNum;
                if (column == 'change_quality') {
                    defaultNum = item.change_quality;
                } else if(column == 'change_qty'){
                    defaultNum = item.change_qty;
                } else {
                    defaultNum = item.change_defect;
                }
                $calculater.open(function (num, dialog) {
                        var oriNum;
                        if (column == 'change_quality') {
                            //oriNum = item.change_quality;
                            var surplus_qty = 0;
                            //20180518 modify by Dustdusk for M#46295: 良品數量不可少於多餘數
                            if(item.abnormal_detail && item.abnormal_detail.length > 0){
                                item.abnormal_detail.forEach(function(detai){
                                    if(detai.abnormal_type == '11'){
                                        surplus_qty = $calculater.decimalAdd((+surplus_qty), (+detai.defect_qty));
                                    }
                                });
                            }
                            if((+num)>=surplus_qty){
                                item.change_quality = num;
                                angular.element(target).removeClass('is-focus');
                                dialog.hide();
                                //$scope.total_change_qty = $scope.total_change_qty + parseInt(num) - parseInt(oriNum);
                            } else {
                                $scope.$root.showAlert($filter('translate')('B0301.msg.qty_ls_surplus_qty', {surplus_qty:surplus_qty}));
                            }
                        } else if(column == 'change_qty'){
                            oriNum = item.change_qty;
                            item.change_qty = num;
                            angular.element(target).removeClass('is-focus');
                            dialog.hide();
                        } else {
                            oriNum = item.change_defect;
                            item.change_defect = num;
                            $scope.total_change_qty = $scope.total_change_qty + parseInt(num) - parseInt(oriNum);
                            if (item.change_defect != item.ori_defect) {
                                item.is_defect_change = 'Y';
                            }
                            angular.element(target).removeClass('is-focus');
                            dialog.hide();
                        }
                    },
                    function (dialog) {
                        angular.element(target).removeClass('is-focus');
                        dialog.hide();
                    },
                    {
                        defaultNum: defaultNum,
                        decimalLength: 3
                    });
            };
            //用生產批號取得資訊
            function adjustmentPlotInfoGet(content, feedback) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.adjustment_plot_info_get',
                    content: content,
                    success: function (data) {
                        feedback(data);
                    }
                });
            }

            //送出調整資訊
            function adjustmentPlotInfoProcess(content, feedback) {
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.adjustment_plot_info_process',
                    content: content,
                    success: function (data) {
                        feedback(data);
                    }
                });
            }

            //取得生產批調帳歷史資訊
            function adjustmentPlotInfoLogGet(content, feedback){
                $MMWService.pageNumberInfoGet({
                    page_mode:'ADJUSTLOG',
                    query_condition_info:[
                        {column_name:'lotno', query_mode:0, value:content.plot_no, merge_condition_model:'AND' },
                        {column_name:'opno', query_mode:0, value:content.op_no, merge_condition_model:'AND' }
                    ]
                },function(data){
                    feedback(data);
                });
            }

            function genBadType(badReasonList){
                var badTypeList = [];
                var badType = '';
                badReasonList.forEach(function(badReason){
                    if(badType!=badReason.reason_type){
                        badTypeList.push({
                            reason_type:badReason.reason_type,
                            reason_sub_type:badReason.reason_sub_type
                        });
                        badType = badReason.reason_type;
                    }
                });
                return badTypeList;
            }

            $scope.toggleContent = function(content_name){
                if(content_name == 'adjustment_currently_detail_hide'){
                    $scope.adjustInfo.adjustment_currently_detail_hide = !$scope.adjustInfo.adjustment_currently_detail_hide;
                } else if(content_name == 'adjustment_detail_hide'){
                    $scope.adjustInfo.adjustment_detail_hide = !$scope.adjustInfo.adjustment_detail_hide;
                }
            }

            //20170612 modify by Dustdusk for 增加輸入不良原因
            $scope.loadAbnormalDetail = function(plotInfo, index){
                var prev_surplus_qty = 0;
                if(!plotInfo.abnormal_detail){
                    plotInfo.abnormal_detail = [];
                } else {
                    //取出原本的多餘數
                    plotInfo.abnormal_detail.forEach(function(detail){
                        if(detail.abnormal_type == '11'){
                            prev_surplus_qty = $calculater.decimalAdd((+prev_surplus_qty), (+detail.defect_qty));
                        }
                    });
                }
                // 20220506 modify by Alan for#95492 : 修改良數(修)計算方式，不良數(修)僅顯示不良(defect_qty_sum)
                $AbnormalService.init({
                    plotInfo:plotInfo,
                    confirm:function(dialog){
                        //20180518 modify by Dustdusk for M#46295: 調整良品/不良品計算邏輯
                        var defect_qty_sum = 0, // 不良
                            total_surplus_qty = 0; /// 多餘
                            total_lack_qty = 0; // 短少
                        dialog.plotInfo.abnormal_detail.forEach(function(detail){
                            if(detail.abnormal_type == '0'){
                                defect_qty_sum = $calculater.decimalAdd((+defect_qty_sum), (+detail.defect_qty));
                            } else if(detail.abnormal_type == '11'){
                                total_surplus_qty = $calculater.decimalAdd((+total_surplus_qty), (+detail.defect_qty));
                            } else if(detail.abnormal_type == '12'){
                                total_lack_qty = $calculater.decimalAdd((+total_lack_qty), (+detail.defect_qty));
                            }
                        });
                        var change_quality = calculateChangeQty(dialog.plotInfo.inputqty, total_surplus_qty, total_lack_qty, defect_qty_sum);
                        if (change_quality < 0) {
                            $scope.$root.showAlert($filter('translate')('B0301.msg.modify_qty_less_than_zero'));
                            return
                        }
                        if(plotInfo.change_defect != defect_qty_sum){
                            plotInfo.change_defect = defect_qty_sum;//不良數
                            plotInfo.is_defect_change = 'Y';
                        }
                        if(plotInfo.change_quality != change_quality){
                            plotInfo.change_quality = change_quality;
                        }            
                        // 20220613 modify by Alan for#95492 : 保存修改後加總值
                        $scope.change_surplus_qty_total[index] = total_surplus_qty;
                        $scope.change_lack_qty_total[index] = total_lack_qty;
                        dialog.hide();
                    }
                });
            };

            // 20220506 modify by Alan for#95492 : 良數(修)計算函數
            // 計算良數(修) 出站數 + 多餘 - 短少 - 不良
            function calculateChangeQty(inputQty, surplusQty, lackQty, defectQty) {
                var result = 0;
                result = $calculater.decimalAdd(+inputQty, +surplusQty);
                result = $calculater.decimalSub(result, +lackQty);
                result = $calculater.decimalSub(result, +defectQty);

                return result;
            }

            $scope.loadHistory = function(item){
                var content = {
                    plot_no : item.plot_no,
                    op_no : item.op_no
                };
                adjustmentPlotInfoLogGet(content, function(data){
                    openHistoryDialog(item, data);
                });

            };

            function openHistoryDialog(plotInfo,history_list){
                $mdDialog.dialog(
                    'module/moduleB/program/B0301/B0301_history.tmp.html',
                    function(dialog){
                        return {
                            plotInfo:plotInfo,
                            history_list:history_list,
                            back : function(){
                                dialog.hide();
                            }
                        }
                    }
                );
            }

            // 人時開窗修改
            $scope.changeLaborHours = function(item){
                $mdDialog.dialog(
                    'module/moduleB/program/B0301/B0301_employees_detail.tmp.html',
                    function(dialog){
                        return {
                            employees_detail: item.employees_detail,
                            back: function(){
                                dialog.hide();
                            },
                            confirm: function(){
                                var allResvalue = dialog.employees_detail.map(function(item){
                                    return +(item.RESVALUE);
                                });
                                var sum = 0,
                                    point_length = [],
                                    m;
                                for(var i = 0; i < allResvalue.length; i++){

                                    if(allResvalue[i].toString().split(".")[1] == undefined){
                                        point_length.push(0);      
                                    } else {
                                        point_length.push(allResvalue[i].toString().split('.')[1].length);
                                    };
                                    
                                    m = Math.pow(10, Math.max.apply(null, point_length));

                                    sum += Math.round(allResvalue[i] * m);
                                };
                                
                                item.change_labor_hours = (sum / m);

                                dialog.hide();
                            }
                        }
                    }
                );
            };

            // 20220124 modify by Alan for#95492 : 增加新增使用者功能
            //20210412 add by johnsyu for#89899：調帳作業增加多人產量修改的功能
            // 多人產量開窗修改
            $scope.multiple_open = function (item) {
                $mdDialog.dialog(
                    'module/moduleB/program/B0301/B0301_multiple_open.html',
                    function (dialog) {
                        return {
                            employees_detail: [...item.employees_detail],
                            showAddRow: false,
                            isAdd: {},
                            back: function () {
                                dialog.hide();
                            },
                            check_employee_no: function () {                                      
                                $MMWService.showQueryListPNIG({
                                 page_mode: 'user_no_info_get',
                                  pageRecord: 50,
                                  condition: [
                                          { name: $filter('translate')('common.queryList.employee_c'), column_name: 'UserNo', query_mode: '2', value: '' }
                                  ],
                                  header: [
                                          { label: $filter('translate')('common.queryList.employee_c'), code: 'user_no' },
                                          { label: $filter('translate')('common.queryList.employee_n'), code: 'user_name' }
                                  ],
                                  setCondition: function (conditions) {
                                          conditions.push(
                                                  { column_name: 'IssueState', query_mode: '0', value: '2', merge_condition_model: 'AND' }
                                          );
                                          return conditions;
                                  },
                                  selectCode: '',
                                  confirm: function (selectItem, dialog2) {

                                        let obj = {
                                          USERNAME:selectItem.user_name,
                                          USERNO:selectItem.user_no
                                        };
                                        dialog.employees_detail.push(obj);
                                      
                                  }
                            });  
                         },
                            CheckQty: function (event, inputqty, index) {
                                var OriginalValue = Math.round(item.change_quality);
                                var target = event.currentTarget;
                                angular.element(target).addClass('is-focus');
                                $calculater.open(function (num, calcDialog) {
                                    if ((+num) <= OriginalValue) {
                                        dialog.employees_detail[index].inputqty = num;
                                        angular.element(target).removeClass('is-focus');
                                        calcDialog.hide();
                                    } else {
                                        $scope.$root.showAlert($filter('translate')('B0301.msg.check_value') + OriginalValue);
                                    }
                                },
                                    function (calcDialog)
                                    {
                                        angular.element(target).removeClass('is-focus');
                                        calcDialog.hide();
                                    },
                                    {
                                        defaultNum: item.inputqty,
                                        decimal: true
                                        //decimalLength: 3
                                    });
                            },
                            confirm: function () {

                                var OriginalValue = Math.round(item.change_quality);
                                var ResultValue = dialog.employees_detail.map(function (item) {
                                    return +(item.inputqty);
                                });
                                var check = 0,
                                    check_final = 0;

                                for (var i = 0; i < ResultValue.length; i++) {

                                    check = Math.round(ResultValue[i])
                                    if (check > OriginalValue) {
                                        $scope.$root.showAlert($filter('translate')('B0301.msg.check_value') + OriginalValue);
                                        check_final++;
                                    } 
                                };

                                if (check_final == 0) {
                                    item.employees_detail = dialog.employees_detail; 
                                    dialog.hide();
                                }
                            },
                            employeesQueryList: function(old_user) {
                                $scope.$root.showQueryList({
                                    currentEmployees: dialog.employees_detail,
                                    key:'user_no',
                                    pageRecord: 50,
                                    header : [
                                        { label: $filter('translate')('common.queryList.employee_c'), code: 'user_no' },
                                        { label: $filter('translate')('common.queryList.employee_n'), code: 'user_name' }
                                    ],
                                    condition: [
                                        { name: $filter('translate')('common.queryList.employee_c'), column_name: 'UserNo', query_mode: '2', value: old_user && old_user.UserNo || '' }
                                    ],
                                    query: function(conditions, feedback){
                                        var employees = this.currentEmployees;
                                        $MMWService.pageNumberInfoGet({
                                            page_mode : 'user_no_info_get',
                                            query_condition_info : conditions
                                        }, function(itemList){
                                            itemList = $filter('filter')(itemList, nameExpression);
                                            feedback(itemList);
                                            // 過濾掉已選擇的使用者
                                            function nameExpression(value, index, array) {
                                                var isExist = true;
                                                employees.forEach(function(elem) {
                                                    if(elem.USERNO === value.user_no) {
                                                        isExist = false;
                                                    }
                                                });
                                                return isExist
                                            }
                                        });
                                    },
                                    selectCode: old_user && old_user.user_no || '',
                                    confirm: function(selectItem, dialog2){
                                        if (old_user) {
                                            // 更換已選user
                                            var targetIndex = dialog.employees_detail.indexOf(old_user);
                                            dialog.employees_detail[targetIndex] = {
                                                USERNO: selectItem.user_no,
                                                USERNAME: selectItem.user_name,
                                                RESVALUE: dialog.employees_detail[targetIndex].RESVALUE,
                                                inputqty: dialog.employees_detail[targetIndex].inputqty,
                                            };
                                        } else {
                                            // 新增user
                                            dialog.employees_detail.push({
                                                USERNO: selectItem.user_no,
                                                USERNAME: selectItem.user_name,
                                                RESVALUE: '0.0000',
                                                inputqty: '0.0000',
                                            });
                                        }
                                        // 顯示放大鏡
                                        dialog.isAdd[selectItem.user_no] = true;
                                        // 關閉新增使用者
                                        dialog.showAddRow = false;
                                        dialog2.hide();
                            }
                                });
                            },
                        }
                    }
                );
            };

            // 20220613 modify by Alan for#95492 : 依據瑕疵類別回傳加總值
            var getAbnormalQtyTotalBy = function(abnormalDetail, abnormalType) {
                const total = abnormalDetail
                    .filter((elem) => Number(elem.abnormal_type) === Number(abnormalType))
                    .reduce((total, surplusElem) => total + Number(surplusElem.defect_qty), 0);
                return total;
            }

            var resetAbnormalQtyTotal = function() {
                $scope.ori_surplus_qty_total = [];
                $scope.ori_lack_qty_total = [];
                $scope.change_surplus_qty_total = [];
                $scope.change_lack_qty_total = [];
            }
        }
    ]
});
